package com.cxy.datawarehouse.interceptor;

import cn.hutool.core.util.StrUtil;
import com.cxy.datawarehouse.annotation.NotLogin;
import com.cxy.datawarehouse.entity.User;
import com.cxy.datawarehouse.exception.BizException;
import com.cxy.datawarehouse.response.ResultStatus;
import com.cxy.datawarehouse.threadLogin.UserInfoContextHolder;
import com.cxy.datawarehouse.utils.TokenUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录校验器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Class<?> beanType = handlerMethod.getBeanType();
            if (beanType.isAnnotationPresent(NotLogin.class)) {
                return true;
            }
            if (handlerMethod.getMethod().isAnnotationPresent(NotLogin.class)) {
                return true;
            }

            String token = request.getHeader("token");
            if (StrUtil.isBlank(token)) {
                throw new BizException(ResultStatus.NOT_LOGIN.getMessage());
            }
            User userSession = TokenUtils.getUserSession(token);
            UserInfoContextHolder.setLoginInfo(userSession);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if (handler instanceof HandlerMethod) {
            UserInfoContextHolder.remove();
        }
    }
}
